<!DOCTYPE html><html class="theme-next gemini use-motion" lang="zh-CN"><head><meta name="generator" content="Hexo 3.9.0"><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=2"><meta name="theme-color" content="#222"><link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2"><link rel="stylesheet" href="/css/main.css?v=7.1.1"><link rel="apple-touch-icon" sizes="180x180" href="/images/my-apple-touch-icon-next.png?v=7.1.1"><link rel="icon" type="image/png" sizes="32x32" href="/images/my-32x32-next.png?v=7.1.1"><link rel="icon" type="image/png" sizes="16x16" href="/images/my-16x16-next.png?v=7.1.1"><link rel="mask-icon" href="/images/my-logo.svg?v=7.1.1" color="#222"><script id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '7.1.1',
    sidebar: {"position":"left","display":"post","offset":12,"onmobile":false,"dimmer":false},
    back2top: true,
    back2top_sidebar: false,
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script><meta name="description" content="对 C/C++ 字节对齐、位域和柔型数组成员的总结与一些示例分析"><meta name="keywords" content="C语言,C++,C,字节对齐,位域,柔型数组,示例"><meta property="og:type" content="article"><meta property="og:title" content="C&#x2F;C++字节对齐"><meta property="og:url" content="https://renshengjihe.cn/190616-CCppByteAlign.html"><meta property="og:site_name" content="dhd的博客"><meta property="og:description" content="对 C/C++ 字节对齐、位域和柔型数组成员的总结与一些示例分析"><meta property="og:locale" content="zh-CN"><meta property="og:image" content="https://renshengjihe.cn/190616-CCppByteAlign/1_1.png"><meta property="og:image" content="https://renshengjihe.cn/190616-CCppByteAlign/1_2.png"><meta property="og:image" content="https://renshengjihe.cn/190616-CCppByteAlign/1_3.png"><meta property="og:updated_time" content="2019-11-18T07:46:11.985Z"><meta name="twitter:card" content="summary"><meta name="twitter:title" content="C&#x2F;C++字节对齐"><meta name="twitter:description" content="对 C/C++ 字节对齐、位域和柔型数组成员的总结与一些示例分析"><meta name="twitter:image" content="https://renshengjihe.cn/190616-CCppByteAlign/1_1.png"><link rel="canonical" href="https://renshengjihe.cn/190616-CCppByteAlign"><script id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script><title>C/C++字节对齐 | dhd的博客</title><noscript><style>
  .use-motion .motion-element,
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-title { opacity: initial; }

  .use-motion .logo,
  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style></noscript></head><body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN"><div class="container sidebar-position-left page-post-detail"><div class="headband"></div><header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader"><div class="header-inner"><div class="site-brand-wrapper"><div class="site-meta"><div class="custom-logo-site-title"><a href="/" class="brand" rel="start"><span class="logo-line-before"><i></i></span> <span class="site-title">dhd的博客</span><span class="logo-line-after"><i></i></span></a></div><h1 class="site-subtitle" itemprop="description">对酒当歌，人生几何</h1></div><div class="site-nav-toggle"> <button aria-label="切换导航栏"><span class="btn-bar"></span><span class="btn-bar"></span><span class="btn-bar"></span></button></div></div><nav class="site-nav"><ul id="menu" class="menu"><li class="menu-item menu-item-home"><a href="/" rel="section"><i class="menu-item-icon fa fa-fw fa-home"></i><br>首页</a></li><li class="menu-item menu-item-tags"><a href="/tags/" rel="section"><i class="menu-item-icon fa fa-fw fa-tags"></i><br>标签</a></li><li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="menu-item-icon fa fa-fw fa-th"></i><br>分类</a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="menu-item-icon fa fa-fw fa-archive"></i><br>归档</a></li></ul></nav></div></header><main id="main" class="main"><div class="main-inner"><div class="content-wrap"><div id="content" class="content"><div id="posts" class="posts-expand"><article class="post post-type-normal" itemscope itemtype="http://schema.org/Article"><div class="post-block"><link itemprop="mainEntityOfPage" href="https://renshengjihe.cn/190616-CCppByteAlign.html"><span hidden itemprop="author" itemscope itemtype="http://schema.org/Person"><meta itemprop="name" content="dhd"><meta itemprop="description" content="个人博客,分享一些C/C++ Linux 相关的学习笔记"><meta itemprop="image" content="/images/avatar.gif"></span><span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization"><meta itemprop="name" content="dhd的博客"></span><header class="post-header"><h2 class="post-title" itemprop="name headline">C/C++字节对齐</h2><div class="post-meta"><span class="post-time"><span class="post-meta-item-icon"><i class="fa fa-calendar-o"></i></span> <span class="post-meta-item-text">发表于</span> <time title="创建时间：2019-06-16 14:12:33" itemprop="dateCreated datePublished" datetime="2019-06-16T14:12:33+08:00">2019-06-16</time> <span class="post-meta-divider">|</span><span class="post-meta-item-icon"><i class="fa fa-calendar-check-o"></i></span> <span class="post-meta-item-text">更新于</span> <time title="修改时间：2019-11-18 15:46:11" itemprop="dateModified" datetime="2019-11-18T15:46:11+08:00">2019-11-18</time></span> <span class="post-category"><span class="post-meta-divider">|</span><span class="post-meta-item-icon"><i class="fa fa-folder-o"></i></span> <span class="post-meta-item-text">分类于</span> <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/C-C/" itemprop="url" rel="index"><span itemprop="name">C/C++</span></a></span></span> <span class="post-comments-count"><span class="post-meta-divider">|</span><span class="post-meta-item-icon"><i class="fa fa-comment-o"></i></span> <span class="post-meta-item-text">评论数：</span><a href="/190616-CCppByteAlign.html#comments" itemprop="discussionUrl"><span class="post-comments-count valine-comment-count" data-xid="/190616-CCppByteAlign.html" itemprop="commentCount"></span></a></span> <span id="/190616-CCppByteAlign.html" class="leancloud_visitors" data-flag-title="C/C++字节对齐"><span class="post-meta-divider">|</span><span class="post-meta-item-icon"><i class="fa fa-eye"></i></span> <span class="post-meta-item-text">阅读次数：</span><span class="leancloud-visitors-count"></span></span><div class="post-description">对 C/C++ 字节对齐、位域和柔型数组成员的总结与一些示例分析</div></div></header><div class="post-body" itemprop="articleBody"><p>对 C/C++ 字节对齐、位域和柔型数组成员的总结与一些示例分析</p><a id="more"></a><h2 id="字节对齐"><a href="#字节对齐" class="headerlink" title="字节对齐"></a>字节对齐</h2><h3 id="什么是字节对齐"><a href="#什么是字节对齐" class="headerlink" title="什么是字节对齐"></a>什么是字节对齐</h3><p>现代计算机中内存空间都是按照byte划分的，从理论上讲似乎对任何类型的变量的访问可以从任何地址开始，但实际情况是在访问特定类型变量的时候经常在特定的内存地址访问，这就需要各种类型数据按照一定的规则在空间上排列，而不是顺序的一个接一个的排放，这就是对齐。</p><h3 id="为什么有字节对齐"><a href="#为什么有字节对齐" class="headerlink" title="为什么有字节对齐"></a>为什么有字节对齐</h3><p>字节对齐主要是通过牺牲一部分存储空间来换取时间的方式，可以通过下面的例子来理解字节对齐的意义：<br><img src="/190616-CCppByteAlign/1_1.png" alt="图1_1"></p><ul><li>图1是没有对齐的情况，要取出double型的数据，需要进行三次寻址。然后将三次取得的数据拼接成完整的数据。</li><li>图2是有对齐的情况，只需寻址两次，但相应的char后面的3字节空间不能够使用了。</li></ul><h3 id="四个概念"><a href="#四个概念" class="headerlink" title="四个概念"></a>四个概念</h3><p>在考虑字节对齐相关的问题时，需要遵循下面四点：</p><ol><li>基本数据类型的自身对齐值</li></ol><table><thead><tr><th style="text-align:right">数据类型</th><th style="text-align:left">对齐值</th></tr></thead><tbody><tr><td style="text-align:right">char</td><td style="text-align:left">1</td></tr><tr><td style="text-align:right">short</td><td style="text-align:left">2</td></tr><tr><td style="text-align:right">int</td><td style="text-align:left">4</td></tr><tr><td style="text-align:right">long</td><td style="text-align:left">4</td></tr><tr><td style="text-align:right">float</td><td style="text-align:left">4</td></tr><tr><td style="text-align:right">double</td><td style="text-align:left">8</td></tr></tbody></table><ol start="2"><li><p>程序的指定对齐值</p><p> 可以通过预编译命令认为指定程序的对齐值</p><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 指定对齐值为4</span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">pragma</span> pack(4)</span></span><br><span class="line"><span class="comment">// 恢复默认对齐值</span></span><br><span class="line"><span class="meta">#progma pack()</span></span><br></pre></td></tr></table></figure></li><li><p>自定义类型的自身对齐值，取内部成员对齐值最大的一个。</p><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">Test</span></span></span><br><span class="line"><span class="class">&#123;</span></span><br><span class="line">    <span class="keyword">int</span> a;</span><br><span class="line">    <span class="keyword">double</span> b;</span><br><span class="line">    <span class="keyword">char</span> c;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure><p> 结构体Test的对齐值为 8 ，大小为 24</p></li><li><p>自定义类型的有效对齐值，程序指定对齐值和自身对齐中最小的一个。</p><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#progma pack(4)</span></span><br><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">Test</span></span></span><br><span class="line"><span class="class">&#123;</span></span><br><span class="line">    <span class="keyword">char</span> a;</span><br><span class="line">    <span class="keyword">short</span> b;</span><br><span class="line">    <span class="keyword">char</span> c;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure><p> 结构体Test的对齐值为 2 ，大小为 6</p></li></ol><h3 id="字节对齐问题实例分析"><a href="#字节对齐问题实例分析" class="headerlink" title="字节对齐问题实例分析"></a>字节对齐问题实例分析</h3><p>下面的例子指针为 4 字节大小，默认对齐值为 8</p><h4 id="例-1-结构体嵌套"><a href="#例-1-结构体嵌套" class="headerlink" title="例 1 结构体嵌套"></a>例 1 结构体嵌套</h4><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// sizeof(Test) = 40</span></span><br><span class="line"><span class="keyword">typedef</span> <span class="class"><span class="keyword">struct</span> <span class="title">Test</span></span></span><br><span class="line"><span class="class">&#123;</span></span><br><span class="line">    <span class="keyword">short</span> a;       <span class="comment">// 2 +6 -&gt; 8</span></span><br><span class="line">    <span class="class"><span class="keyword">struct</span></span></span><br><span class="line"><span class="class">    &#123;</span></span><br><span class="line">        <span class="keyword">int</span> b;     <span class="comment">// 4 +4 -&gt; 8</span></span><br><span class="line">        <span class="keyword">double</span> c;  <span class="comment">// 8</span></span><br><span class="line">        <span class="keyword">char</span> d;    <span class="comment">// 1 +7 -&gt; 8</span></span><br><span class="line">    &#125;;                  </span><br><span class="line">    <span class="keyword">long</span> e;        <span class="comment">// 4 +4 -&gt; 8</span></span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure><p>解释：b、c、d 依然是结构体 Test 的成员，结构体对齐值为 8</p><h4 id="例-2-程序指定对齐值"><a href="#例-2-程序指定对齐值" class="headerlink" title="例 2 程序指定对齐值"></a>例 2 程序指定对齐值</h4><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// sizeof(Test) = 24</span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">pragma</span> pack(4)</span></span><br><span class="line"><span class="keyword">typedef</span> <span class="class"><span class="keyword">struct</span> <span class="title">Test</span></span></span><br><span class="line"><span class="class">&#123;</span></span><br><span class="line">    <span class="keyword">short</span> a;       <span class="comment">// 2 +2 -&gt; 4</span></span><br><span class="line">    <span class="class"><span class="keyword">struct</span></span></span><br><span class="line"><span class="class">    &#123;</span></span><br><span class="line">        <span class="keyword">int</span> b;     <span class="comment">// 4</span></span><br><span class="line">        <span class="keyword">double</span> c;  <span class="comment">// 8</span></span><br><span class="line">        <span class="keyword">char</span> d;    <span class="comment">// 1 +3 -&gt; 4</span></span><br><span class="line">    &#125;;                  </span><br><span class="line">    <span class="keyword">long</span> e;        <span class="comment">// 4</span></span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure><p>解释：指定了对齐值为 4，比 4 小的补齐，比 4 大的需为 4 的整数倍</p><h4 id="例-3-嵌套结构体定义的坑"><a href="#例-3-嵌套结构体定义的坑" class="headerlink" title="例 3 嵌套结构体定义的坑"></a>例 3 嵌套结构体定义的坑</h4><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// sizeof(Test) = 8</span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">pragma</span> pack(8)</span></span><br><span class="line"><span class="keyword">typedef</span> <span class="class"><span class="keyword">struct</span> <span class="title">Test</span></span></span><br><span class="line"><span class="class">&#123;</span></span><br><span class="line">    <span class="keyword">short</span> a;       <span class="comment">// 2 +2 -&gt; 4</span></span><br><span class="line">    <span class="class"><span class="keyword">struct</span> <span class="title">t</span>       // 这里结构体有名，相当于没有</span></span><br><span class="line"><span class="class">    &#123;</span></span><br><span class="line">        <span class="keyword">int</span> b;    </span><br><span class="line">        <span class="keyword">double</span> c;  </span><br><span class="line">        <span class="keyword">char</span> d;    </span><br><span class="line">    &#125;;                  </span><br><span class="line">    <span class="keyword">long</span> e;        <span class="comment">// 4</span></span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure><p>解释：<code>struct t</code>有名就是定义结构体，不占空间。</p><h4 id="例-4-数组成员"><a href="#例-4-数组成员" class="headerlink" title="例 4 数组成员"></a>例 4 数组成员</h4><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// sizeof(Test) = 112</span></span><br><span class="line"><span class="keyword">typedef</span> <span class="class"><span class="keyword">struct</span> <span class="title">Test</span></span></span><br><span class="line"><span class="class">&#123;</span></span><br><span class="line">    <span class="keyword">short</span> a;            <span class="comment">// 2 +6 -&gt; 8</span></span><br><span class="line">    <span class="class"><span class="keyword">struct</span></span></span><br><span class="line"><span class="class">    &#123;</span></span><br><span class="line">        <span class="keyword">int</span> b;          <span class="comment">// 4 +4 -&gt; 8</span></span><br><span class="line">        <span class="keyword">double</span> c[<span class="number">10</span>];   <span class="comment">// 80</span></span><br><span class="line">        <span class="keyword">char</span> d;         <span class="comment">// 1 +7 -&gt; 8</span></span><br><span class="line">    &#125;;                  </span><br><span class="line">    <span class="keyword">long</span> e;             <span class="comment">// 4 +4 -&gt; 8</span></span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure><p>解释：数组可以理解为 10 个连续的 double 成员</p><h4 id="例-5-柔性数组成员"><a href="#例-5-柔性数组成员" class="headerlink" title="例 5 柔性数组成员"></a>例 5 柔性数组成员</h4><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// sizeof(Test) = 8</span></span><br><span class="line"><span class="keyword">typedef</span> <span class="class"><span class="keyword">struct</span> <span class="title">Test</span></span></span><br><span class="line"><span class="class">&#123;</span></span><br><span class="line">    <span class="keyword">short</span> a;       </span><br><span class="line">    <span class="keyword">int</span> b;</span><br><span class="line">    <span class="keyword">char</span> c[<span class="number">0</span>];  <span class="comment">// 柔性数组，必须在最后一个位置</span></span><br><span class="line">&#125;;</span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">char</span> *str = <span class="string">"fdsafsfsdafsdf"</span>;</span><br><span class="line">    Test *pt = (Test*)<span class="built_in">malloc</span>(<span class="keyword">sizeof</span>(Test) + </span><br><span class="line">                <span class="keyword">sizeof</span>(<span class="keyword">char</span>)*(<span class="built_in">strlen</span>(str)+<span class="number">1</span>) );</span><br><span class="line">    pt-&gt;c = (<span class="keyword">char</span>*)<span class="built_in">malloc</span>();</span><br><span class="line">    <span class="built_in">strcpy</span>(pt-&gt;c, str);</span><br><span class="line">    <span class="built_in">free</span>(pt);   <span class="comment">// 只需要释放一次</span></span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>解释：柔型数组成员不占空间，只起到一个占位符的作用，在需要的时候，可以分配给此结构体更大的空间，然后用柔性数组成员作为变量名进行访问。并且不用像指针成员那样考虑内存释放。</p><p>如上代码中的做法就是用柔型数组成员来存储字符串，图示如下：<br><img src="/190616-CCppByteAlign/1_2.png" alt="图1_2"></p><h4 id="例-6-位域"><a href="#例-6-位域" class="headerlink" title="例 6 位域"></a>例 6 位域</h4><p>位域对一个字节的内存空间进行了更加精细的划分，指定变量只能占用一个字节数据中的指定位数</p><ul><li>位域不能跨字节存储</li><li>位域不能跨类型存储</li></ul><p>看下面两个例子：<br></p><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// sizeof(Test) = 2</span></span><br><span class="line"><span class="keyword">typedef</span> <span class="class"><span class="keyword">struct</span> <span class="title">Test</span></span></span><br><span class="line"><span class="class">&#123;</span></span><br><span class="line">    <span class="keyword">char</span> a : <span class="number">1</span>;     <span class="comment">// 位域 只占 1 个 bit位</span></span><br><span class="line">    <span class="keyword">char</span> b : <span class="number">3</span>;     <span class="comment">// 占 3 个 bit 位</span></span><br><span class="line">    <span class="keyword">char</span> c : <span class="number">3</span>;     <span class="comment">// 占 3 个 bit 位</span></span><br><span class="line">    <span class="keyword">char</span> d : <span class="number">2</span>;     <span class="comment">// 占 2 个 bit 位   另起炉灶</span></span><br><span class="line">    <span class="comment">// 位域不夸字节存储</span></span><br><span class="line">&#125;Test;</span><br></pre></td></tr></table></figure><p></p><p>如图所示：<br><img src="/190616-CCppByteAlign/1_3.png" alt="图1_3"><br></p><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// sizeof(Test) = 8</span></span><br><span class="line"><span class="keyword">typedef</span> <span class="class"><span class="keyword">struct</span> <span class="title">Test</span></span></span><br><span class="line"><span class="class">&#123;</span></span><br><span class="line">    <span class="keyword">char</span> a : <span class="number">4</span>; <span class="comment">// 位域不能够跨类型存储</span></span><br><span class="line">    <span class="keyword">int</span> b : <span class="number">5</span>;</span><br><span class="line">&#125;Test;</span><br></pre></td></tr></table></figure><p></p><h4 id="例-7-联合体-union"><a href="#例-7-联合体-union" class="headerlink" title="例 7 联合体 union"></a>例 7 联合体 union</h4><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// sizeof(Test) = 8</span></span><br><span class="line"><span class="keyword">typedef</span> <span class="keyword">union</span> Test</span><br><span class="line">&#123;</span><br><span class="line">    <span class="keyword">char</span> a;</span><br><span class="line">    <span class="keyword">double</span> b;</span><br><span class="line">    <span class="keyword">int</span> c;</span><br><span class="line">&#125;Test;</span><br></pre></td></tr></table></figure><p>解释：联合体取最大的一个大小，在笔试时务必看清是 union 还是 struct.</p><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 96</span></span><br><span class="line"><span class="keyword">typedef</span> <span class="keyword">union</span> Test</span><br><span class="line">&#123;</span><br><span class="line">    <span class="keyword">short</span> a;</span><br><span class="line">    <span class="class"><span class="keyword">struct</span></span></span><br><span class="line"><span class="class">    &#123;</span></span><br><span class="line">        <span class="keyword">int</span> b;</span><br><span class="line">        <span class="keyword">double</span> c[<span class="number">10</span>];</span><br><span class="line">        <span class="keyword">char</span> d;</span><br><span class="line">    &#125;;</span><br><span class="line">    <span class="keyword">long</span> e;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>解释：联合体中嵌套结构体，必须保证能够被整个存下。</p><h4 id="例-9-枚举-enum"><a href="#例-9-枚举-enum" class="headerlink" title="例 9 枚举 enum"></a>例 9 枚举 enum</h4><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// sizeof(Test) = 4</span></span><br><span class="line"><span class="keyword">typedef</span> <span class="keyword">enum</span> Test</span><br><span class="line">&#123;</span><br><span class="line">    ADD=<span class="number">-100</span>,</span><br><span class="line">    SUB,        <span class="comment">// -99</span></span><br><span class="line">    MUL=<span class="number">100</span>,</span><br><span class="line">    DIV,        <span class="comment">// 101</span></span><br><span class="line">    MOD</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure><p>解释：枚举类型占4个字节，</p><ul><li>枚举值默认从0开始</li><li>若自定义了其中一个的值，则下面的值在上面的基础上+1</li></ul><h4 id="例-10-静态成员"><a href="#例-10-静态成员" class="headerlink" title="例 10 静态成员"></a>例 10 静态成员</h4><figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// sizeof(Test) = 24</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Test</span></span></span><br><span class="line"><span class="class">&#123;</span></span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">    <span class="keyword">static</span> <span class="keyword">int</span> a;</span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">    <span class="keyword">char</span> a;</span><br><span class="line">    <span class="keyword">double</span> b;</span><br><span class="line">    <span class="keyword">int</span> *p;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure><p>解释：静态成员不占结构体空间</p><h4 id="例-11-继承"><a href="#例-11-继承" class="headerlink" title="例 11 继承"></a>例 11 继承</h4><figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// sizeof(Test) = 48</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Base</span></span></span><br><span class="line"><span class="class">&#123;</span></span><br><span class="line"><span class="keyword">private</span>:</span><br><span class="line">    <span class="keyword">char</span> x;</span><br><span class="line">    <span class="keyword">double</span> y;</span><br><span class="line">    <span class="keyword">int</span> *z;</span><br><span class="line">&#125;;</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Test</span> :</span> <span class="keyword">public</span> Base</span><br><span class="line">&#123;</span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">    <span class="keyword">char</span> a;</span><br><span class="line">    <span class="keyword">double</span> b;</span><br><span class="line">    <span class="keyword">int</span> *p;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure><p>解释：无论何种继承方式，子类都会继承父类的成员，不同的只是访问权限。</p><h4 id="例-12-虚函数"><a href="#例-12-虚函数" class="headerlink" title="例 12 虚函数"></a>例 12 虚函数</h4><figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// sizeof(Test) = 16</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Test</span></span></span><br><span class="line"><span class="class">&#123;</span></span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">    Test()&#123;&#125;</span><br><span class="line">    <span class="keyword">virtual</span> ~Test()&#123;&#125;</span><br><span class="line"><span class="keyword">private</span>:</span><br><span class="line">    <span class="keyword">char</span> a;</span><br><span class="line">    <span class="keyword">int</span> b;</span><br><span class="line">    <span class="keyword">int</span> *p;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>解释：出现虚函数时，虚表指针会占一个指针大小的空间</p></div><footer class="post-footer"><div class="post-tags"> <a href="/tags/C-C/" rel="tag"># C/C++</a></div><div class="post-nav"><div class="post-nav-next post-nav-item"><a href="/190613-CPointer.html" rel="next" title="C指针总结"><i class="fa fa-chevron-left"></i> C指针总结</a></div><span class="post-nav-divider"></span><div class="post-nav-prev post-nav-item"> <a href="/190629-CppInheritance.html" rel="prev" title="C++继承、多态与虚表分析">C++继承、多态与虚表分析<i class="fa fa-chevron-right"></i></a></div></div></footer></div></article></div></div><div class="comments" id="comments"></div></div><div class="sidebar-toggle"><div class="sidebar-toggle-line-wrap"><span class="sidebar-toggle-line sidebar-toggle-line-first"></span><span class="sidebar-toggle-line sidebar-toggle-line-middle"></span><span class="sidebar-toggle-line sidebar-toggle-line-last"></span></div></div><aside id="sidebar" class="sidebar"><div class="sidebar-inner"><ul class="sidebar-nav motion-element"><li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap"> 文章目录</li><li class="sidebar-nav-overview" data-target="site-overview-wrap"> 站点概览</li></ul><div class="site-overview-wrap sidebar-panel"><div class="site-overview"><div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person"><p class="site-author-name" itemprop="name">dhd</p><div class="site-description motion-element" itemprop="description">个人博客,分享一些C/C++ Linux 相关的学习笔记</div></div><nav class="site-state motion-element"><div class="site-state-item site-state-posts"> <a href="/archives/"><span class="site-state-item-count">16</span> <span class="site-state-item-name">日志</span></a></div><div class="site-state-item site-state-categories"> <a href="/categories/"><span class="site-state-item-count">7</span> <span class="site-state-item-name">分类</span></a></div><div class="site-state-item site-state-tags"> <a href="/tags/"><span class="site-state-item-count">8</span> <span class="site-state-item-name">标签</span></a></div></nav><div class="links-of-author motion-element"><span class="links-of-author-item"><a href="mailto:donghaodong555@foxmail.com" title="E-Mail &rarr; mailto:donghaodong555@foxmail.com" rel="noopener" target="_blank"><i class="fa fa-fw fa-envelope"></i></a></span></div></div></div><div class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active"><div class="post-toc"><div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#字节对齐"><span class="nav-number">1.</span> <span class="nav-text">字节对齐</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#什么是字节对齐"><span class="nav-number">1.1.</span> <span class="nav-text">什么是字节对齐</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#为什么有字节对齐"><span class="nav-number">1.2.</span> <span class="nav-text">为什么有字节对齐</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#四个概念"><span class="nav-number">1.3.</span> <span class="nav-text">四个概念</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#字节对齐问题实例分析"><span class="nav-number">1.4.</span> <span class="nav-text">字节对齐问题实例分析</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#例-1-结构体嵌套"><span class="nav-number">1.4.1.</span> <span class="nav-text">例 1 结构体嵌套</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#例-2-程序指定对齐值"><span class="nav-number">1.4.2.</span> <span class="nav-text">例 2 程序指定对齐值</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#例-3-嵌套结构体定义的坑"><span class="nav-number">1.4.3.</span> <span class="nav-text">例 3 嵌套结构体定义的坑</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#例-4-数组成员"><span class="nav-number">1.4.4.</span> <span class="nav-text">例 4 数组成员</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#例-5-柔性数组成员"><span class="nav-number">1.4.5.</span> <span class="nav-text">例 5 柔性数组成员</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#例-6-位域"><span class="nav-number">1.4.6.</span> <span class="nav-text">例 6 位域</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#例-7-联合体-union"><span class="nav-number">1.4.7.</span> <span class="nav-text">例 7 联合体 union</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#例-9-枚举-enum"><span class="nav-number">1.4.8.</span> <span class="nav-text">例 9 枚举 enum</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#例-10-静态成员"><span class="nav-number">1.4.9.</span> <span class="nav-text">例 10 静态成员</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#例-11-继承"><span class="nav-number">1.4.10.</span> <span class="nav-text">例 11 继承</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#例-12-虚函数"><span class="nav-number">1.4.11.</span> <span class="nav-text">例 12 虚函数</span></a></li></ol></li></ol></li></ol></div></div></div></div></aside></div></main><footer id="footer" class="footer"><div class="footer-inner"><div class="copyright">&copy; <span itemprop="copyrightYear">2019</span><span class="with-love" id="animate"><i class="fa fa-user"></i></span> <span class="author" itemprop="copyrightHolder">dhd</span></div></div></footer><div class="back-to-top"><i class="fa fa-arrow-up"></i></div></div><script>
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script><script color="0,0,255" opacity="0.5" zindex="-1" count="99" src="/lib/canvas-nest/canvas-nest.min.js"></script><script src="/lib/jquery/index.js?v=2.1.3"></script><script src="/lib/velocity/velocity.min.js?v=1.2.1"></script><script src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script><script src="/js/utils.js?v=7.1.1"></script><script src="/js/motion.js?v=7.1.1"></script><script src="/js/affix.js?v=7.1.1"></script><script src="/js/schemes/pisces.js?v=7.1.1"></script><script src="/js/scrollspy.js?v=7.1.1"></script><script src="/js/post-details.js?v=7.1.1"></script><script src="/js/next-boot.js?v=7.1.1"></script><script src="//cdn1.lncld.net/static/js/3.11.1/av-min.js"></script><script src="//unpkg.com/valine/dist/Valine.min.js"></script><script>
  var GUEST = ['nick', 'mail', 'link'];
  var guest = 'nick,mail,link';
  guest = guest.split(',').filter(function(item) {
    return GUEST.indexOf(item) > -1;
  });
  new Valine({
    el: '#comments',
    verify: false,
    notify: false,
    appId: 'f6cPnWydCEaioX6iq6AoSBPz-gzGzoHsz',
    appKey: 'TRF9THIRqNFdQRvrCURnmfBG',
    placeholder: 'Just go go',
    avatar: 'mm',
    meta: guest,
    pageSize: '10' || 10,
    visitor: false,
    lang: '' || 'zh-cn'
  });
</script><script>
    
    function addCount(Counter) {
      var $visitors = $('.leancloud_visitors');
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();

      Counter('get', '/classes/Counter', { where: JSON.stringify({ url }) })
        .done(function({ results }) {
          if (results.length > 0) {
            var counter = results[0];
            
            Counter('put', '/classes/Counter/' + counter.objectId, JSON.stringify({ time: { '__op': 'Increment', 'amount': 1 } }))
            
              .done(function() {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.time + 1);
              })
            
              .fail(function ({ responseJSON }) {
                console.log('Failed to save Visitor num, with error message: ' + responseJSON.error);
              })
          } else {
            
              Counter('post', '/classes/Counter', JSON.stringify({ title: title, url: url, time: 1 }))
                .done(function() {
                  var $element = $(document.getElementById(url));
                  $element.find('.leancloud-visitors-count').text(1);
                })
                .fail(function() {
                  console.log('Failed to create');
                });
            
          }
        })
        .fail(function ({ responseJSON }) {
          console.log('LeanCloud Counter Error: ' + responseJSON.code + ' ' + responseJSON.error);
        });
    }
    

    $(function() {
      $.get('https://app-router.leancloud.cn/2/route?appId=' + 'hrnLXd6od62r2eJJ9yYsWO74-gzGzoHsz')
        .done(function({ api_server }) {
          var Counter = function(method, url, data) {
            return $.ajax({
              method: method,
              url: 'https://' + api_server + '/1.1' + url,
              headers: {
                'X-LC-Id': 'hrnLXd6od62r2eJJ9yYsWO74-gzGzoHsz',
                'X-LC-Key': 'N3zDUUUGyqewKV2RLoozARF2',
                'Content-Type': 'application/json',
              },
              data: data
            });
          };
          
            addCount(Counter);
          
        });
    });
  </script><script>
    (function(){
      var bp = document.createElement('script');
      var curProtocol = window.location.protocol.split(':')[0];
      bp.src = (curProtocol === 'https') ? 'https://zz.bdstatic.com/linksubmit/push.js' : 'http://push.zhanzhang.baidu.com/push.js';
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(bp, s);
    })();
  </script><script>
  $('.highlight').not('.gist .highlight').each(function(i, e) {
    var $wrap = $('<div>').addClass('highlight-wrap');
    $(e).after($wrap);
    $wrap.append($('<button>').addClass('copy-btn').append('复制').on('click', function(e) {
      var code = $(this).parent().find('.code').find('.line').map(function(i, e) {
        return $(e).text();
      }).toArray().join('\n');
      var ta = document.createElement('textarea');
      var yPosition = window.pageYOffset || document.documentElement.scrollTop;
      ta.style.top = yPosition + 'px'; // Prevent page scroll
      ta.style.position = 'absolute';
      ta.style.opacity = '0';
      ta.readOnly = true;
      ta.value = code;
      document.body.appendChild(ta);
      ta.select();
      ta.setSelectionRange(0, code.length);
      ta.readOnly = false;
      var result = document.execCommand('copy');
      
        if (result) $(this).text('复制成功');
        else $(this).text('复制失败');
      
      ta.blur(); // For iOS
      $(this).blur();
    })).on('mouseleave', function(e) {
      var $b = $(this).find('.copy-btn');
      setTimeout(function() {
        $b.text('复制');
      }, 300);
    }).append(e);
  })
</script></body></html>